/**
 * @Author: LiMeng
 * @Date: 2017/4/10
 */
var GLOBAL = {
    DATA_GRID_ROW_INDEX: {
        dg1: 0,
        dg2: 0
    }
};
var attachEditRowEvent = function (dataGridId) {
    $('body').on('click', '[id^=' + dataGridId + '_btn_edit_]', function () {
        var id = this.id.replace(dataGridId + '_btn_edit_', '');
        var dgEle = '#' + dataGridId;
        var index = $(dgEle).datagrid('getRowIndex', id);
        $(dgEle).datagrid('selectRow', index).datagrid('beginEdit', index);
        $(this).addClass('hide');
        $('#' + dataGridId + '_btn_save_' + id).removeClass('hide');
        $('#' + dataGridId + '_btn_delete_' + id).addClass('hide');
        $('#' + dataGridId + '_btn_cancel_' + id).removeClass('hide');
    });
};
var attachSaveRowEvent = function (dataGridId, url) {
    $('body').on('click', 'a[id^=' + dataGridId + '_btn_save_]', function () {
        var $this = $(this);
        var id = this.id.replace(dataGridId + '_btn_save_', '');
        var dgEle = '#' + dataGridId;
        var index = $(dgEle).datagrid('getRowIndex', id);
        if ($(dgEle).datagrid('validateRow', index)) {
            $(dgEle).datagrid('collapseRow', index);
            $(dgEle).datagrid('endEdit', index);
            $.ajax({
                method: 'POST',
                dataType: 'json',
                url: url,
                data: $(dgEle).datagrid('getSelected'),
                success: function (result) {
                    if (result.success) {
                        $.messager.progress('close');	// 如果提交成功则隐藏进度条
                        layer.msg(result.message, {time: 1000, icon: 1}, function () {
                            $this.addClass('hide');
                            $('#' + dataGridId + '_btn_edit_' + id).removeClass('hide');
                            $('#' + dataGridId + '_btn_delete_' + id).removeClass('hide');
                            $('#' + dataGridId + '_btn_cancel_' + id).addClass('hide');
                        });
                    } else {
                        $.messager.progress('close');
                        layer.msg(result.message, {time: 1000, icon: 2});
                    }
                }
            });
        }
    });
};
var attachCancelRowEvent = function (dataGridId) {
    $('body').on('click', 'a[id^=' + dataGridId + '_btn_cancel_]', function () {
        var id = this.id.replace(dataGridId + '_btn_cancel_', '');
        var dgEle = '#' + dataGridId;
        var index = $(dgEle).datagrid('getRowIndex', id);
        $(dgEle).datagrid('cancelEdit', index);
        $(dgEle).datagrid('collapseRow', index);
        $(this).addClass('hide');
        $('#' + dataGridId + '_btn_save_' + id).addClass('hide');
        $('#' + dataGridId + '_btn_edit_' + id).removeClass('hide');
        $('#' + dataGridId + '_btn_delete_' + id).removeClass('hide');
    });
};
var attachDeleteRowEvent = function (dataGridId, url) {
    $('body').on('click', 'a[id^=' + dataGridId + '_btn_delete_]', function () {
        var $this = $(this);
        var layIndex = layer.confirm('确定删除本条数据吗？', function () {
            var id = $this[0].id.replace(dataGridId + '_btn_delete_', '');
            var dgEle = '#' + dataGridId;
            var index = $(dgEle).datagrid('getRowIndex', id);
            $.ajax({
                method: 'POST',
                dataType: 'json',
                url: url,
                data: {
                    id: $(dgEle).datagrid('getSelected').id
                },
                success: function (result) {
                    if (result.success) {
                        layer.msg(result.message, {time: 1000, icon: 1}, function () {
                            $(dgEle).datagrid('deleteRow', index);
                        });
                    } else {
                        layer.msg(result.message, {time: 1000, icon: 2});
                    }
                }
            });
            layer.close(layIndex);
        });
    });
};
var attachAddRowEvent = function (dataGridId, url) {
    $('#' + dataGridId + '_btn_add').on('click', function () {
        var id = $.generateUUID();
        $.ajax({
            method: 'POST',
            dataType: 'json',
            url: url,
            data: {
                id: id,
                contractorId: $(':input[name=id]').val()
            },
            success: function (result) {
                if (!result.success) {
                    layer.msg(result.message, {time: 1000, icon: 2});
                    return false;
                }
                $('#' + dataGridId).datagrid('insertRow', {
                        index: GLOBAL.DATA_GRID_ROW_INDEX[dataGridId],
                        row: {
                            id: id,
                            contractorId: $(':input[name=id]').val()
                        }
                    }
                ).datagrid('selectRow', GLOBAL.DATA_GRID_ROW_INDEX[dataGridId]).datagrid('beginEdit', GLOBAL.DATA_GRID_ROW_INDEX[dataGridId]);
                $('#' + dataGridId + '_btn_edit_' + id).addClass('hide');
                $('#' + dataGridId + '_btn_save_' + id).removeClass('hide');
                $('#' + dataGridId + '_btn_delete_' + id).addClass('hide');
                $('#' + dataGridId + '_btn_cancel_' + id).removeClass('hide');
                GLOBAL.DATA_GRID_ROW_INDEX[dataGridId] += 1;
            }
        });
    });
};
var attachFileRowEvent = function (dataGridId, url) {
    $('body').on('click', '[id^=' + dataGridId + '_btn_file_]', function () {
        var id = this.id.replace(dataGridId + '_btn_file_', '');
        var dgEle = '#' + dataGridId;
        var index = $(dgEle).datagrid('getRowIndex', id);
        var uploadUserId = $(':input[name=uploadUserId]').val();
        var packageKey = 'safeProductCert';
        var layerIndex = parent.layer.open({
            type: 2,
            title: '上传附件',
            area: ['500px', '300px'],
            content: ROOT_PATH + '/accessory/fileUpload.shtml?resourceId=' + $.getQueryParam('resourceId') + '&uploadUserId=' + uploadUserId + '&businessId=' + id + '&packageKey=' + packageKey,
            cancel: function (index, layero) {
                var params = layero.find('iframe').contents().find(':input').serializeJson();
                if ($.isEmptyObject(params)) {
                    return true;
                }
                $.extend(params, {
                    id: id,
                    contractorId: $(':input[name=id]').val()
                });
                $.ajax({
                    method: 'POST',
                    dataType: 'json',
                    url: url,
                    data: params,
                    success: function (result) {
                        if (result.success) {
                            parent.layer.msg(result.message, {time: 1000, icon: 1}, function () {
                                parent.layer.close(layerIndex);
                            });
                        } else {
                            parent.layer.msg(result.message, {time: 1000, icon: 2});
                        }
                    }
                });
                return false;
            }
        });
    });
};
$(function () {
    var EMPTY_OPTION = {
        code: '',
        name: '请选择'
    };
    var IS_FIRST_SET_COMBOBOX_VALUE = true;//是否是初次设置下拉框值

    /**
     * 根据数据初始化城市下拉框
     * @param initialCityArray
     */
    var initCityComboBox = function (initialCityArray) {
        //初始化城市下拉框
        $('#city').combobox({
            valueField: 'code',
            textField: 'name',
            editable: false,
            data: initialCityArray,
            onSelect: function (record) {
                if (IS_FIRST_SET_COMBOBOX_VALUE) {
                    $.ajax({
                        method: 'GET',
                        dataType: 'JSON',
                        url: ROOT_PATH + "/permission/district/county.shtml?parentCode=" + record.code,
                        success: function (data) {
                            data.unshift(EMPTY_OPTION);
                            initCountyComboBox(data);
                        }
                    });
                }
            },
            onClick: function (record) {
                if (record.code === '') {
                    $('#county').combobox('clear').combobox('loadData', [EMPTY_OPTION]);
                    return true;
                }
                $.ajax({
                    method: 'GET',
                    dataType: 'JSON',
                    url: ROOT_PATH + "/permission/district/county.shtml?parentCode=" + record.code,
                    success: function (data) {
                        data.unshift(EMPTY_OPTION);
                        $('#county').combobox('clear').combobox('loadData', data);
                    }
                });
            }
        });
    };

    /**
     * 根据数据初始化区县下拉框
     * @param initialCountyArray
     */
    var initCountyComboBox = function (initialCountyArray) {
        //初始化区县下拉框
        $('#county').combobox({
            valueField: 'code',
            textField: 'name',
            editable: false,
            data: initialCountyArray
        });
        IS_FIRST_SET_COMBOBOX_VALUE = false;
    };

    //初始化国家下拉框
    $('#country').combobox({
        url: ROOT_PATH + "/permission/district/country.shtml",
        valueField: 'code',
        textField: 'name',
        editable: false,
        loadFilter: function (data) {
            data.unshift(EMPTY_OPTION);
            return data;
        },
        onSelect: function (record) {
            if (record.name.toString() === '中国') {
                $('.district-wrap').show();
            } else {
                $('.district-wrap').hide();
            }
        }
    });

    //初始化省份下拉框
    $('#province').combobox({
        url: ROOT_PATH + "/permission/district/province.shtml",
        valueField: 'code',
        textField: 'name',
        editable: false,
        loadFilter: function (data) {
            data.unshift(EMPTY_OPTION);
            return data;
        },
        onSelect: function (record) {
            if (IS_FIRST_SET_COMBOBOX_VALUE) {
                $.ajax({
                    method: 'GET',
                    dataType: 'JSON',
                    url: ROOT_PATH + "/permission/district/city.shtml?parentCode=" + record.code,
                    success: function (data) {
                        data.unshift(EMPTY_OPTION);
                        initCityComboBox(data);
                    }
                });
            }
        },
        onClick: function (record) {
            if (record.code === '') {
                $('#city').combobox('clear').combobox('loadData', [EMPTY_OPTION]);
                $('#county').combobox('clear').combobox('loadData', [EMPTY_OPTION]);
                return true;
            }
            $.ajax({
                method: 'GET',
                dataType: 'JSON',
                url: ROOT_PATH + "/permission/district/city.shtml?parentCode=" + record.code,
                success: function (data) {
                    data.unshift(EMPTY_OPTION);
                    $('#city').combobox('clear').combobox('loadData', data);
                    $('#county').combobox('clear').combobox('loadData', [EMPTY_OPTION]);
                }
            });
        }
    });

    //初始化加载datagrid
    $('#dg1').datagrid({
        method: 'post',
        url: ROOT_PATH + '/contractor/safeProductCert/list.shtml',
        queryParams: {
            contractorId: $.getQueryParam('id'),
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: false,
        height: 300,
        singleSelect: true,
        view: detailview,
        detailFormatter: function (index, row) {
            return '<div style="padding:2px"><span>变更信息</span><table class="ddv"></table></div>';
        },
        columns: [[
            {field: 'ckid', checkbox: true},
            {
                field: 'action', title: '操作', width: 80, align: 'center', formatter: function (value, row, index) {
                var ele_edit = '<a id="dg1_btn_edit_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">编辑</a> ';
                var ele_save = '<a id="dg1_btn_save_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary hide" plain="true">保存</a> ';
                var ele_delete = '<a id="dg1_btn_delete_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">删除</a>';
                var ele_cancel = '<a id="dg1_btn_cancel_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary hide" plain="true">取消</a>';
                return ele_edit + ele_save + ele_delete + ele_cancel;
            }
            },
            {
                field: 'name',
                title: '证书名称',
                width: 100,
                sortable: true,
                editor: {
                    type: 'combobox', options: {
                        editable: false,
                        data: [{
                            value: '安全生产许可证',
                            text: '安全生产许可证'
                        }, {
                            value: '其他证书',
                            text: '其他证书'
                        }],
                        required: true
                    }
                }
            },
            {
                field: 'certCode',
                title: '证书编号',
                width: 100,
                sortable: true,
                editor: {type: 'validatebox', options: {required: true}}
            },
            {
                field: 'validStartDate',
                title: '开始日期',
                width: 80,
                sortable: true,
                editor: {type: 'datebox', options: {required: true, validateOnBlur: true}}
            },
            {
                field: 'validEndDate',
                title: '结束日期',
                width: 80,
                sortable: true,
                editor: {type: 'datebox', options: {required: true, validateOnBlur: true}}
            },
            {
                field: 'accessory', title: '附件', width: 50, align: 'center', formatter: function (value, row, index) {
                return '<a id="dg1_btn_file_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">附件</a> ';
            }
            },
            {field: 'updateTime', title: '最后修改时间', width: 100, sortable: true},
            {field: 'contractorId', title: '承包商id', hidden: true}
        ]],
        onExpandRow: function (index, row) {
            var ddv = $(this).datagrid('getRowDetail', index).find('table.ddv');
            ddv.datagrid({
                url: ROOT_PATH + '/contractor/safeProductCert/historyList.shtml',
                queryParams: {
                    contractorId: $.getQueryParam('id'),
                    certId: row.id,
                    sort: 'addTime',
                    order: 'desc'
                },
                fitColumns: true,
                singleSelect: true,
                rownumbers: true,
                loadMsg: '',
                height: 'auto',
                columns: [[
                    {field: 'name', title: '证书名称', width: 100},
                    {field: 'certCode', title: '证书编号', width: 80},
                    {field: 'validStartDate', title: '开始日期', width: 80},
                    {field: 'validEndDate', title: '结束日期', width: 80},
                    {field: 'addUserName', title: '变更人', width: 80},
                    {field: 'addTime', title: '变更时间', width: 100},
                    {field: 'addDeptName', title: '变更部门', width: 80},
                    {field: 'addUserId', title: '变更人Id', width: 80, hidden: true},
                    {field: 'addDeptId', title: '变更部门Id', width: 80, hidden: true}
                ]],
                onResize: function () {
                    $('#dg1').datagrid('fixDetailRowHeight', index);
                },
                onLoadSuccess: function () {
                    setTimeout(function () {
                        $('#dg1').datagrid('fixDetailRowHeight', index);
                    }, 0);
                }
            });
            $('#dg1').datagrid('fixDetailRowHeight', index);
        }
    });

    //初始化加载datagrid
    $('#dg2').datagrid({
        method: 'post',
        url: ROOT_PATH + '/contractor/businessQualification/list.shtml',
        queryParams: {
            contractorId: $.getQueryParam('id'),
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: false,
        height: 300,
        singleSelect: true,
        view: detailview,
        detailFormatter: function (index, row) {
            return '<div style="padding:2px"><span>变更信息</span><table class="ddv"></table></div>';
        },
        columns: [[
            {field: 'ckid', checkbox: true},
            {
                field: 'action', title: '操作', width: 80, align: 'center', formatter: function (value, row, index) {
                var ele_edit = '<a id="dg2_btn_edit_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">编辑</a> ';
                var ele_save = '<a id="dg2_btn_save_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary hide" plain="true">保存</a> ';
                var ele_delete = '<a id="dg2_btn_delete_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">删除</a>';
                var ele_cancel = '<a id="dg2_btn_cancel_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary hide" plain="true">取消</a>';
                return ele_edit + ele_save + ele_delete + ele_cancel;
            }
            },
            {
                field: 'name',
                title: '业务资质名称',
                width: 100,
                sortable: true,
                editor: {
                    type: 'validatebox', options: {required: true}
                }
            },
            {
                field: 'level',
                title: '业务资质等级',
                width: 100,
                sortable: true,
                formatter: function (value, row, index) {
                    if (typeof value === 'undefined' || value === null || value === '') {
                        return '无';
                    }
                    return $.getChineseInteger(value) + '级';
                },
                editor: {
                    type: 'combobox', options: {
                        editable: false,
                        data: [
                            {
                                value: '',
                                text: '请选择'
                            },
                            {
                                value: 1,
                                text: '一级'
                            }, {
                                value: 2,
                                text: '二级'
                            }, {
                                value: 3,
                                text: '三级'
                            }, {
                                value: 4,
                                text: '四级'
                            }],
                        required: true
                    }
                }
            },
            {
                field: 'certCode',
                title: '业务资质编号',
                width: 100,
                sortable: true,
                editor: {type: 'validatebox', options: {required: true}}
            },
            {
                field: 'validStartDate',
                title: '开始日期',
                width: 80,
                sortable: true,
                editor: {type: 'datebox', options: {required: true, validateOnBlur: true}}
            },
            {
                field: 'validEndDate',
                title: '结束日期',
                width: 80,
                sortable: true,
                editor: {type: 'datebox', options: {required: true, validateOnBlur: true}}
            },
            {
                field: 'accessory', title: '附件', width: 50, align: 'center', formatter: function (value, row, index) {
                return '<a id="dg2_btn_file_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">附件</a> ';
            }
            },
            {field: 'updateTime', title: '最后修改时间', width: 100, sortable: true},
            {field: 'contractorId', title: '承包商id', hidden: true}
        ]],
        onExpandRow: function (index, row) {
            var ddv = $(this).datagrid('getRowDetail', index).find('table.ddv');
            ddv.datagrid({
                url: ROOT_PATH + '/contractor/businessQualification/historyList.shtml',
                queryParams: {
                    contractorId: $.getQueryParam('id'),
                    businessId: row.id,
                    sort: 'addTime',
                    order: 'desc'
                },
                fitColumns: true,
                singleSelect: true,
                rownumbers: true,
                loadMsg: '',
                height: 'auto',
                columns: [[
                    {field: 'name', title: '业务资质名称', width: 100},
                    {
                        field: 'level', title: '业务资质等级', width: 100, formatter: function (value) {
                        if (typeof value === 'undefined' || value === null || value === '') {
                            return '无';
                        }
                        return $.getChineseInteger(value) + '级';
                    }
                    },
                    {field: 'certCode', title: '资质证书编号', width: 80},
                    {field: 'validStartDate', title: '开始日期', width: 80},
                    {field: 'validEndDate', title: '结束日期', width: 80},
                    {field: 'addUserName', title: '变更人', width: 80},
                    {field: 'addTime', title: '变更时间', width: 100},
                    {field: 'addDeptName', title: '变更部门', width: 80},
                    {field: 'addUserId', title: '变更人Id', width: 80, hidden: true},
                    {field: 'addDeptId', title: '变更部门Id', width: 80, hidden: true}
                ]],
                onResize: function () {
                    $('#dg2').datagrid('fixDetailRowHeight', index);
                },
                onLoadSuccess: function () {
                    setTimeout(function () {
                        $('#dg2').datagrid('fixDetailRowHeight', index);
                    }, 0);
                }
            });
            $('#dg2').datagrid('fixDetailRowHeight', index);
        }
    });

    $('#btn_save').on('click', function () {
        $.messager.progress();	// 显示进度条
        $('#form1').form('submit', {
            url: ROOT_PATH + '/contractor/contractorInfo/edit.shtml',
            onSubmit: function (param) {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// 如果表单是无效的则隐藏进度条
                }
                return isValid;	// 返回false终止表单提交
            },
            success: function (result) {
                result = $.parseJSON(result);
                if (result.success) {
                    $.messager.progress('close');	// 如果提交成功则隐藏进度条
                    layer.msg(result.message, {time: 1000, icon: 1}, function () {
                        $.getIframeWindow().$('#dg1').datagrid('load');
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    });
                } else {
                    $.messager.progress('close');	// 如果提交成功则隐藏进度条
                    layer.msg(result.message, {icon: 2});
                }
            }
        });
    });

    // 证书信息
    //添加按钮
    attachAddRowEvent('dg1', ROOT_PATH + '/contractor/safeProductCert/save.shtml');
    //每行的编辑按钮
    attachEditRowEvent('dg1');
    //每行的保存按钮
    attachSaveRowEvent('dg1', ROOT_PATH + '/contractor/safeProductCert/update.shtml');
    //每行的取消按钮
    attachCancelRowEvent('dg1');
    //每行的删除按钮
    attachDeleteRowEvent('dg1', ROOT_PATH + '/contractor/safeProductCert/delete.shtml');
    //每行的附件按钮
    attachFileRowEvent('dg1', ROOT_PATH + '/contractor/safeProductCert/upload.shtml');

    //业务资质信息
    //添加按钮
    attachAddRowEvent('dg2', ROOT_PATH + '/contractor/businessQualification/save.shtml');
    //每行的编辑按钮
    attachEditRowEvent('dg2');
    //每行的保存按钮
    attachSaveRowEvent('dg2', ROOT_PATH + '/contractor/businessQualification/update.shtml');
    //每行的取消按钮
    attachCancelRowEvent('dg2');
    //每行的删除按钮
    attachDeleteRowEvent('dg2', ROOT_PATH + '/contractor/businessQualification/delete.shtml');
    //每行的附件按钮
    attachFileRowEvent('dg2', ROOT_PATH + '/contractor/businessQualification/upload.shtml');
});